package com.zk.babala.activity;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.FocusHighlightHelper;
import androidx.leanback.widget.GridLayoutManager;
import androidx.leanback.widget.ItemBridgeAdapter;
import androidx.leanback.widget.VerticalGridView;
import androidx.recyclerview.widget.RecyclerView;

import com.open.androidtvwidget.keyboard.SkbContainer;
import com.open.androidtvwidget.keyboard.SoftKey;
import com.open.androidtvwidget.keyboard.SoftKeyBoardListener;
import com.zk.babala.BabalaApp;
import com.zk.babala.R;
import com.zk.babala.entity.Movie;
import com.zk.babala.presenter.MovieItemPresenter;
import com.zk.babala.presenter.SearchHistoryAdapter;
import com.zk.babala.util.HistoryUtil;
import com.zk.babala.util.RequestUtil;

import java.util.List;


public class SearchActivity extends Activity {
    EditText input_tv;
    VerticalGridView verticalGridView;
    Button searchButton;
    SkbContainer skbContainer;
    ListView keysListView;
    int currPage = 0;
    ArrayObjectAdapter objectAdapter;
    // 在Activity中添加以下成员变量
    private GridView searchHistoryList;
    private Button clearHistoryButton;
    private SearchHistoryAdapter searchHistoryAdapter;
    private List<String> searchHistoryData;
    LinearLayout leftLinerLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_activity);
        input_tv = findViewById(R.id.search_text);
        searchButton = findViewById(R.id.searchButton);
        keysListView = findViewById(R.id.keyListView);
        leftLinerLayout = findViewById(R.id.leftLinerLayout);
        initSearchHistory();
        initSkbContainer();
        initSearchGridView();
        searchButton.setOnClickListener(view -> {
            keysListView.setVisibility(View.GONE);
            search(input_tv.getText().toString());
        });
        keysListView.setOnItemClickListener((parent, view, position, id) -> {
            Object item = parent.getItemAtPosition(position);
            leftLinerLayout.setVisibility(View.GONE);
            search(item.toString());
        });
        verticalGridView.post(() -> {
            skbContainer.requestFocus();
            loadHis();
        });

    }

    private void searchKey() {
        List<String> keys = RequestUtil.getSuggest(input_tv.getText().toString());
        if (!keys.isEmpty()) {
            keysListView.setVisibility(View.VISIBLE);
            ArrayAdapter<String> adapter = new ArrayAdapter<>(SearchActivity.this, android.R.layout.simple_list_item_1, keys);
            keysListView.setAdapter(adapter);
        } else {
            keysListView.setVisibility(View.GONE);
        }

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (skbContainer.onSoftKeyUp(keyCode, event))
            return true;
        return super.onKeyDown(keyCode, event);
    }

    private void search(String word) {
        List<Movie> list = BabalaApp.getSourceParse().search(word);
        currPage = 0;
        HistoryUtil.getHistoryInstance().saveSearchHistory(word);
        updateSearchHistory();
        if (list.isEmpty()) {
            Toast.makeText(getApplicationContext(), "没有搜索到数据~", Toast.LENGTH_LONG).show();
            currPage = -1;
            return;
        }
        objectAdapter.clear();
        loadData(list);
        verticalGridView.requestFocus();
    }

    private void loadData(List<Movie> list) {
        objectAdapter.addAll(currPage * list.size(), list);
    }

    private long outKeyTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (skbContainer.onSoftKeyDown(keyCode, event))
            return true;
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - outKeyTime) < 1000) {
                this.finish();
            }
            outKeyTime = System.currentTimeMillis();
            if (searchButton.hasFocus()) {
                this.finish();
            } else if (!skbContainer.hasFocus()) {
                leftLinerLayout.setVisibility(View.VISIBLE);
                skbContainer.requestFocus();
                return true;
            } else if (!searchButton.hasFocus()) {
                searchButton.requestFocus();
                return true;
            }

        }

        return super.onKeyDown(keyCode, event);
    }

    private void initSkbContainer() {
        skbContainer = findViewById(R.id.skbContainer);
        skbContainer.setSkbLayout(R.xml.skb_all_key);

        // 监听键盘事件
        skbContainer.setOnSoftKeyBoardListener(new SoftKeyBoardListener() {
            @Override
            public void onCommitText(SoftKey softKey) {
                int keyCode;
                String keyLabel = softKey.getKeyLabel();
                if (!TextUtils.isEmpty(keyLabel)) { // 输入文字.
                    input_tv.setText(String.format("%s%s", input_tv.getText(), softKey.getKeyLabel()));
                    searchKey();
                } else { // 自定义按键，这些都是你自己在XML中设置的keycode.
                    keyCode = softKey.getKeyCode();
                    if (keyCode == KeyEvent.KEYCODE_DEL) {
                        String text = input_tv.getText().toString();
                        if (!TextUtils.isEmpty(text)) {
                            text = text.substring(0, text.length() - 1);
                            input_tv.setText(text);
                            if (TextUtils.isEmpty(text)) {
                                keysListView.setVisibility(View.GONE);
                                loadHis();
                            } else {
                                searchKey();
                            }
                        }
                    }
                }

            }

            @Override
            public void onBack(SoftKey key) {
                searchButton.requestFocus();
            }

            @Override
            public void onDelete(SoftKey key) {
                String text = input_tv.getText().toString();
                input_tv.setText(text.substring(0, text.length() - 1));
            }
        });
    }

    private void initSearchGridView() {
        verticalGridView = findViewById(R.id.search_item_list);
        verticalGridView.setNumColumns(5);
        //监听滑动加载更多数据
        verticalGridView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                recyclerView.post(() -> {
                    GridLayoutManager layoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
                    assert layoutManager != null;
                    int SelectedPosition = verticalGridView.getSelectedPosition();
                    int totalItemCount = layoutManager.getItemCount();
                    if (currPage != -1 && (totalItemCount - SelectedPosition) <= 6) {
                        List<Movie> loadNextList = BabalaApp.getSourceParse().loadNext();
                        if (loadNextList.isEmpty()) {
                            currPage = -1;
                            if (totalItemCount > 12) {
                                Toast.makeText(recyclerView.getContext(), "已经到底啦~~", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            currPage++;
                            loadData(loadNextList);
                        }
                    }
                });

            }
        });

        MovieItemPresenter presenter = new MovieItemPresenter();
        //创建ObjectAdapter，用于提供数据，当有多种类型时，传入PresenterSelector
        objectAdapter = new ArrayObjectAdapter(presenter);
        ItemBridgeAdapter bridgeAdapter = new ItemBridgeAdapter(objectAdapter);
        //将ItemBridgeAdapter传入HorizontalGridView
        verticalGridView.setAdapter(bridgeAdapter);
        //设置上焦动画
        FocusHighlightHelper.setupHeaderItemFocusHighlight(bridgeAdapter);
    }

    private void loadHis() {
        currPage = 0;
        keysListView.setVisibility(View.GONE);
        objectAdapter.clear();
        loadData(HistoryUtil.getHistoryInstance().getHistoryList());
        currPage = -1;
    }

    private void initSearchHistory() {
        searchHistoryList = findViewById(R.id.search_history_list);
        clearHistoryButton = findViewById(R.id.clear_history_button);
        // 获取搜索历史数据
        searchHistoryData = HistoryUtil.getHistoryInstance().getSearchHistory();
        // 设置适配器
        searchHistoryAdapter = new SearchHistoryAdapter(this, searchHistoryData);
        searchHistoryList.setAdapter(searchHistoryAdapter);
        // 点击历史记录项进行搜索
        searchHistoryList.setOnItemClickListener((parent, view, position, id) -> {
            String searchKey = searchHistoryData.get(position);
            EditText searchText = findViewById(R.id.search_text);
            searchText.setText(searchKey);
            search(searchKey);
        });

        // 清除历史记录
        clearHistoryButton.setOnClickListener(v -> {
            HistoryUtil.getHistoryInstance().clearSearchHistory();
            searchHistoryData.clear();
            searchHistoryAdapter.notifyDataSetChanged();
        });
    }

    // 更新搜索历史显示
    private void updateSearchHistory() {
        searchHistoryData.clear();
        searchHistoryData.addAll(HistoryUtil.getHistoryInstance().getSearchHistory());
        searchHistoryAdapter.notifyDataSetChanged();
    }

}